<template>
  <div class="app-container">
    <el-form :model="formData" :rules="rules" ref="formData" label-width="120px">
      <el-form-item label="原密码" prop="oldPwd">
          <el-input type="password" v-model="formData.oldPwd" style="width:30%" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
          <el-input type="password" v-model="formData.newPwd" style="width:30%" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="confPwd">
          <el-input type="password" v-model="formData.confPwd" style="width:30%" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
          <el-button @click="resetForm('formData')">清空</el-button>
          <el-button type="primary" @click="getForm('formData')">确 定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { modPwd } from "@/api/api.verify.js"
export default {
  name: 'Pwd',
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else if(value.length<6){
        callback(new Error('密码不能小于6位'));
      } else {
        if (this.formData.confPwd !== '') {
          this.$refs.formData.validateField('confPwd');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.formData.newPwd) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      formData:{
        oldPwd:'',//原密码
        newPwd:'',//新密码
        confPwd:'',//确认新密码
      },
      rules: {
        oldPwd: [
          {required: true, message: '请输入原密码', trigger: 'blur'},
        ],
        newPwd: [
          { validator: validatePass, trigger: 'blur' },
          {min: 3, max: 35, message: '长度在 2 到 35 个字符', trigger: 'blur'}
        ],
        confPwd: [
          { validator: validatePass2, trigger: 'blur' }
        ],
      },//表单验证
    }
  },
  methods: {
    getForm(formName){
      let _this=this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data=_this.formData;
          modPwd(data).then(d=>{
            if(d.code==1){
              _this.$message({
                  type: 'success',
                  message: '修改成功'
              });
              setTimeout(function(){
                _this.$store.dispatch('user/logout')
                _this.logout()
              },1000)
            }
          });
        }
      });
    },
    resetForm(formName){//表单重置
      this.$refs[formName].resetFields();
    },
    async logout() {//退出登录
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    }

  }
}
</script>